package com.cuit.zuke.system.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cuit.zuke.common.annotation.ControllerEndpoint;
import com.cuit.zuke.common.exception.GlobalException;
import com.cuit.zuke.common.util.Constant;
import com.cuit.zuke.common.util.Result;
import com.cuit.zuke.system.entity.SysMenuEntity;
import com.cuit.zuke.system.service.SysAdminService;
import com.cuit.zuke.system.service.SysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * @program: zuke
 * @description: 系统菜单
 * @author: KamTang
 * @create: 2022-03-31 10:07
 **/
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController extends SysAdminAbstractController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysAdminService adminService;

    /**
     * 导航菜单，菜单的parent_id为0
     */
    @GetMapping("/nav")
    public Result nav() {
        List<SysMenuEntity> menuList = sysMenuService.getNavMenu(getAdmin().getUserId());
        Set<String> permissions = adminService.getUserPermissions(getAdmin().getUserId());
        return Objects.requireNonNull(Result.ok().put("menuList", menuList)).put("permissions",permissions);
    }

    /**
     * 所有菜单列表（封装成父子节点）
     */
    @GetMapping("/list")
    public List<SysMenuEntity> list() {
        List<SysMenuEntity> menuList = sysMenuService.list();
        HashMap<Long, SysMenuEntity> menuMap = new HashMap<>(12);
        for (SysMenuEntity s : menuList) {
            menuMap.put(s.getMenuId(), s);
        }
        for (SysMenuEntity s : menuList) {
            SysMenuEntity parent = menuMap.get(s.getParentId());
            if (Objects.nonNull(parent)) {
                s.setParentName(parent.getName());
            }

        }
        return menuList;
    }


    /**
     * 选择菜单(添加、修改菜单)
     */
    @GetMapping("/select")
    public Result select(){
        //查询列表数据
        List<SysMenuEntity> menuList = sysMenuService.queryNotButtonList();

        //添加顶级菜单
        SysMenuEntity root = new SysMenuEntity();
        root.setMenuId(0L);
        root.setName("一级菜单");
        root.setParentId(-1L);
        root.setOpen(true);
        menuList.add(root);

        return Result.ok().put("menuList", menuList);
    }

    /**
     * 菜单信息
     */
    @GetMapping("/info/{menuId}")
    public Result info(@PathVariable("menuId") Long menuId) {
        SysMenuEntity menu = sysMenuService.getById(menuId);
        return Result.ok().put("menu", menu);
    }

    /**
     * 保存
     */
    @ControllerEndpoint(exceptionMessage = "菜单添加失败", operation = "添加菜单")
    @PostMapping("/save")
    public Result save(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);
        sysMenuService.save(menu);
        return Result.ok();
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    public Result update(@RequestBody SysMenuEntity menu) {
        //数据校验
        verifyForm(menu);
        sysMenuService.updateById(menu);
        return Result.ok();
    }

    /**
     * 删除
     */
    @ControllerEndpoint(exceptionMessage = "菜单删除失败", operation = "删除菜单")
    @PostMapping("/delete/{menuId}")
    public Result delete(@PathVariable("menuId") long menuId){
        if(menuId == 1){
            return Result.error("系统菜单，不能删除");
        }
        //判断是否有子菜单或按钮
        List<SysMenuEntity> menuList = sysMenuService.queryListParentId(menuId);
        if(menuList.size() > 0){
            return Result.error("请先删除子菜单或按钮");
        }
        sysMenuService.delete(menuId);
        return Result.ok();
    }


    /**
     * 验证参数是否正确
     */
    private void verifyForm(SysMenuEntity menu) {
        if (StringUtils.isBlank(menu.getName())) {
            throw new GlobalException("菜单名称不能为空");
        }

        if (menu.getParentId() == null) {
            throw new GlobalException("上级菜单不能为空");
        }

        //菜单
        if (menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (StringUtils.isBlank(menu.getUrl())) {
                throw new GlobalException("菜单URL不能为空");
            }
        }

        //上级菜单类型
        int parentType = Constant.MenuType.CATALOG.getValue();
        if (menu.getParentId() != 0) {
            SysMenuEntity parentMenu = sysMenuService.getById(menu.getParentId());
            parentType = parentMenu.getType();
        }

        //目录、菜单
        if (menu.getType() == Constant.MenuType.CATALOG.getValue() ||
                menu.getType() == Constant.MenuType.MENU.getValue()) {
            if (parentType != Constant.MenuType.CATALOG.getValue()) {
                throw new GlobalException("上级菜单只能为目录类型");
            }
            return;
        }

        //按钮
        if (menu.getType() == Constant.MenuType.BUTTON.getValue()) {
            if (parentType != Constant.MenuType.MENU.getValue()) {
                throw new GlobalException("上级菜单只能为菜单类型");
            }
        }
    }
}
